<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      th:replace="~{modules/layouts/layout :: layout(content = ~{::content}, htmlType = 'page',title = ${singlePage.spec.title + ' | ' + site.title}, head = ~{::head})}">
<th:block th:fragment="head">
    <th:block th:replace="~{modules/common/open-graph :: open-graph(_title = ${singlePage.spec.title},
                _permalink = ${singlePage.status.permalink},
                _cover = ${singlePage.spec.cover},
                _excerpt = ${singlePage.status.excerpt},
                _type = 'website')}"></th:block>
    <!-- 星空专用样式 -->
    <link rel="stylesheet" th:href="${assets_link + '/css/space-entrance.css' + theme_version}">
</th:block>
<th:block th:fragment="content">

    <div class="page" id="body-wrap">
        <!-- 头部导航栏 -->
        <header class="not-top-img" id="page-header">
            <nav th:replace="~{modules/nav :: nav(title = ${singlePage.spec.title})}"></nav>
        </header>
        
        <main class="layout hide-aside" id="content-inner">
            <div id="space-page">
                <!-- 提示文字 -->
                <div class="space-hint" id="spaceHint">
                    <div class="hint-icon">✨</div>
                    <div class="hint-text">点击发光的金色粒子，探索瞬间</div>
                </div>
                
                <!-- 瞬间弹窗 -->
                <div class="moment-modal" id="momentModal">
                    <div class="moment-modal-overlay" onclick="closeMomentModal()"></div>
                    <div class="moment-modal-content">
                        <button class="moment-close" onclick="closeMomentModal()">
                            ×
                        </button>
                        <div class="moment-body" id="momentBody">
                            <div class="moment-loading">
                                <i class="haofont hao-icon-loading"></i>
                                <span>加载中...</span>
                            </div>
                        </div>
                        <div class="moment-actions">
                            <button class="moment-btn" onclick="loadRandomMoment()">
                                <i class="haofont hao-icon-refresh"></i>
                                换一个
                            </button>
                            <a class="moment-btn moment-btn-primary" href="/moments">
                                查看全部
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </main>
        
        <!-- 底部 -->
        <footer th:replace="~{modules/footer}"/>
    </div>
    
    <!-- Three.js 库 -->
    <script type="importmap">
    {
        "imports": {
            "three": "https://cdn.skypack.dev/three@0.136.0",
            "three/addons/": "https://cdn.skypack.dev/three@0.136.0/examples/jsm/"
        }
    }
    </script>
    
    <!-- 星空效果脚本 -->
    <script type="module">
        import * as THREE from "three";
        import {OrbitControls} from "three/addons/controls/OrbitControls.js";
        
        console.clear();
        
        let scene = new THREE.Scene();
        scene.background = new THREE.Color(0x160016);
        let camera = new THREE.PerspectiveCamera(60, innerWidth / innerHeight, 1, 1000);
        camera.position.set(0, 4, 21);
        let renderer = new THREE.WebGLRenderer();
        renderer.setSize(innerWidth, innerHeight);
        document.getElementById('space-page').appendChild(renderer.domElement);
        
        window.addEventListener("resize", event => {
            camera.aspect = innerWidth / innerHeight;
            camera.updateProjectionMatrix();
            renderer.setSize(innerWidth, innerHeight);
        })
        
        let controls = new OrbitControls(camera, renderer.domElement);
        controls.enableDamping = true;
        controls.enablePan = false;
        
        let gu = {
            time: {value: 0}
        }
        
        let sizes = [];
        let shift = [];
        let pushShift = () => {
            shift.push(
                Math.random() * Math.PI, 
                Math.random() * Math.PI * 2, 
                (Math.random() * 0.9 + 0.1) * Math.PI * 0.1,
                Math.random() * 0.9 + 0.1
            );
        }
        
        // 生成普通粒子
        let pts = new Array(50000).fill().map(p => {
            sizes.push(Math.random() * 1.5 + 0.5);
            pushShift();
            return new THREE.Vector3().randomDirection().multiplyScalar(Math.random() * 0.5 + 9.5);
        })
        
        for(let i = 0; i < 100000; i++){
            let r = 10, R = 40;
            let rand = Math.pow(Math.random(), 1.5);
            let radius = Math.sqrt(R * R * rand + (1 - rand) * r * r);
            pts.push(new THREE.Vector3().setFromCylindricalCoords(radius, Math.random() * 2 * Math.PI, (Math.random() - 0.5) * 2 ));
            sizes.push(Math.random() * 1.5 + 0.5);
            pushShift();
        }
        
        let g = new THREE.BufferGeometry().setFromPoints(pts);
        g.setAttribute("sizes", new THREE.Float32BufferAttribute(sizes, 1));
        g.setAttribute("shift", new THREE.Float32BufferAttribute(shift, 4));
        let m = new THREE.PointsMaterial({
            size: 0.125,
            transparent: true,
            depthTest: false,
            blending: THREE.AdditiveBlending,
            onBeforeCompile: shader => {
                shader.uniforms.time = gu.time;
                shader.vertexShader = `
                    uniform float time;
                    attribute float sizes;
                    attribute vec4 shift;
                    varying vec3 vColor;
                    ${shader.vertexShader}
                `.replace(
                    `gl_PointSize = size;`,
                    `gl_PointSize = size * sizes;`
                ).replace(
                    `#include <color_vertex>`,
                    `#include <color_vertex>
                        float d = length(abs(position) / vec3(40., 10., 40));
                        d = clamp(d, 0., 1.);
                        vColor = mix(vec3(227., 155., 0.), vec3(100., 50., 255.), d) / 255.;
                    `
                ).replace(
                    `#include <begin_vertex>`,
                    `#include <begin_vertex>
                        float t = time;
                        float moveT = mod(shift.x + shift.z * t, PI2);
                        float moveS = mod(shift.y + shift.z * t, PI2);
                        transformed += vec3(cos(moveS) * sin(moveT), cos(moveT), sin(moveS) * sin(moveT)) * shift.w;
                    `
                );
                shader.fragmentShader = `
                    varying vec3 vColor;
                    ${shader.fragmentShader}
                `.replace(
                    `#include <clipping_planes_fragment>`,
                    `#include <clipping_planes_fragment>
                        float d = length(gl_PointCoord.xy - 0.5);
                    `
                ).replace(
                    `vec4 diffuseColor = vec4( diffuse, opacity );`,
                    `vec4 diffuseColor = vec4( vColor, smoothstep(0.5, 0.1, d) );`
                );
            }
        });
        let p = new THREE.Points(g, m);
        p.rotation.order = "ZYX";
        p.rotation.z = 0.2;
        scene.add(p)
        
        // 金色粒子相关变量（稍后根据瞬间数量创建）
        let clickableGeo = null;
        let clickableMat = null;
        let clickablePoints = null;
        let numClickable = 0;
        let momentIndices = []; // 存储每个粒子对应的瞬间索引
        let isClickableParticlesCreated = false; // 新增变量，标记是否已创建金色粒子

        // 创建金色粒子的函数（暴露到全局作用域）
        window.createClickableParticles = function(count) {
            // 如果已经有粒子，先移除
            if (clickablePoints) {
                scene.remove(clickablePoints);
            }
            
            const clickablePositions = [];
            const clickableSizes = [];
            numClickable = count;
            momentIndices = [];
            
            for(let i = 0; i < numClickable; i++){
                // 随机分布在星云中
                const angle = Math.random() * Math.PI * 2; // 随机角度
                const radius = 12 + Math.random() * 15; // 距离中心 12-27 单位（随机）
                const y = (Math.random() - 0.5) * 6; // 垂直位置 -3 到 +3（更大范围）
                clickablePositions.push(new THREE.Vector3(
                    Math.cos(angle) * radius,
                    y,
                    Math.sin(angle) * radius
                ));
                clickableSizes.push(12.0); // 金色粒子大小
                momentIndices.push(i); // 每个粒子对应一个瞬间的索引
            }
            
            clickableGeo = new THREE.BufferGeometry().setFromPoints(clickablePositions);
            clickableGeo.setAttribute("sizes", new THREE.Float32BufferAttribute(clickableSizes, 1));
            
            clickableMat = new THREE.PointsMaterial({
            size: 0.125,
            transparent: true,
            depthTest: false,
            blending: THREE.AdditiveBlending,
            onBeforeCompile: shader => {
                shader.uniforms.time = gu.time;
                shader.vertexShader = `
                    uniform float time;
                    attribute float sizes;
                    varying vec3 vColor;
                    ${shader.vertexShader}
                `.replace(
                    `gl_PointSize = size;`,
                    `gl_PointSize = size * sizes;`
                ).replace(
                    `#include <color_vertex>`,
                    `#include <color_vertex>
                        // 更亮的金色，增强发光效果
                        vColor = vec3(1.5, 1.3, 0.3); // 超过1.0会产生发光效果
                    `
                );
                shader.fragmentShader = `
                    varying vec3 vColor;
                    ${shader.fragmentShader}
                `.replace(
                    `#include <clipping_planes_fragment>`,
                    `#include <clipping_planes_fragment>
                        float d = length(gl_PointCoord.xy - 0.5);
                    `
                ).replace(
                    `vec4 diffuseColor = vec4( diffuse, opacity );`,
                    `vec4 diffuseColor = vec4( vColor, smoothstep(0.5, 0.1, d) );`
                );
            }
            });
            clickablePoints = new THREE.Points(clickableGeo, clickableMat);
            scene.add(clickablePoints);
            
            console.log(`✨ 已创建 ${numClickable} 个金色粒子`);
        }
        
        // 鼠标点击检测
        const raycaster = new THREE.Raycaster();
        raycaster.params.Points.threshold = 0.5;
        const mouse = new THREE.Vector2();
        
        renderer.domElement.addEventListener('click', (event) => {
            if (!clickablePoints) return;
            
            mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
            mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
            
            raycaster.setFromCamera(mouse, camera);
            const intersects = raycaster.intersectObject(clickablePoints);
            
            if (intersects.length > 0) {
                // 获取点击的粒子索引
                const particleIndex = intersects[0].index;
                // 显示对应的瞬间
                if (window.showSpecificMoment) {
                    window.showSpecificMoment(particleIndex);
                }
            }
        });
        
        let clock = new THREE.Clock();
        
        renderer.setAnimationLoop(() => {
            controls.update();
            let t = clock.getElapsedTime() * 0.5;
            gu.time.value = t * Math.PI;
            p.rotation.y = t * 0.05;
            
            // 金色粒子闪动效果（从暗淡到明亮的脉动）
            if (clickableGeo && numClickable > 0) {
                const sizes = clickableGeo.attributes.sizes.array;
                for(let i = 0; i < numClickable; i++){
                    // 每个粒子有不同的相位，让它们不同步闪动
                    const phase = (i / numClickable) * Math.PI * 2;
                    const individualPulse = 0.5 + Math.sin(t * 3 + phase) * 0.5;
                    sizes[i] = 12.0 * individualPulse; // 大小范围 0-24（从几乎消失到很亮）
                }
                clickableGeo.attributes.sizes.needsUpdate = true;
            }
            
            renderer.render(scene, camera);

            // 检查并创建金色粒子（确保在 Three.js 初始化完成后，且只创建一次）
            if (window.allMoments && window.allMoments.length > 0 && !isClickableParticlesCreated) {
                if (typeof window.createClickableParticles === 'function') {
                    window.createClickableParticles(window.allMoments.length);
                    isClickableParticlesCreated = true; // 标记已创建
                } else {
                    console.error('createClickableParticles 函数未定义');
                }
            }
        });
        
    </script>
    
    <script th:inline="javascript">
        // 全局变量存储瞬间数据（直接从服务端注入）
        let allMoments = [];
        let currentMoment = null;
        
        // 从服务端渲染的数据构建瞬间数组
        /*<![CDATA[*/
        allMoments = [
            /*[# th:if="${momentFinder != null}"]*/
            /*[# th:each="moment, iterStat : ${momentFinder.listAll()}"]*/
            {
                spec: {
                    content: {
                        html: /*[[${moment.spec.content.html}]]*/ '',
                        raw: /*[[${moment.spec.content.raw}]]*/ '',
                        medium: [
                            /*[# th:if="${moment.spec.content.medium != null}"]*/
                            /*[# th:each="media : ${moment.spec.content.medium}"]*/
                            {
                                url: /*[[${media.url}]]*/ '',
                                type: { name: /*[[${media.type.name}]]*/ '' }
                            },
                            /*[/]*/
                            /*[/]*/
                        ]
                    },
                    releaseTime: /*[[${moment.spec.releaseTime}]]*/ ''
                },
                metadata: {
                    creationTimestamp: /*[[${moment.metadata.creationTimestamp}]]*/ ''
                }
            },
            /*[/]*/
            /*[/]*/
        ];
        /*]]>*/
        
        // 清理数组（移除空元素）
        allMoments = allMoments.filter(m => m && m.spec && m.spec.content);
        
        // 将 allMoments 赋值给 window.allMoments，以便 Three.js 模块脚本访问
        window.allMoments = allMoments;

        console.log('✓ 已从服务端加载瞬间数量:', allMoments.length);
        if (allMoments.length > 0) {
            console.log('第一条瞬间示例:', allMoments[0]);
            // 等待 Three.js 初始化完成后再创建金色粒子
            // setTimeout(() => {
            //     if (typeof window.createClickableParticles === 'function') {
            //         window.createClickableParticles(allMoments.length);
            //     } else {
            //         console.error('createClickableParticles 函数未定义');
            //     }
            // }, 1000);
        }
    </script>
    
    <script>
        // 显示指定索引的瞬间（暴露到全局作用域）
        window.showSpecificMoment = function(index) {
            const modal = document.getElementById('momentModal');
            modal.classList.add('active');
            loadSpecificMoment(index);
        }
        
        // 显示随机瞬间
        function showRandomMoment() {
            const modal = document.getElementById('momentModal');
            modal.classList.add('active');
            loadRandomMoment();
        }
        
        // 加载指定索引的瞬间
        function loadSpecificMoment(index) {
            const momentBody = document.getElementById('momentBody');
            
            if (allMoments.length === 0 || index < 0 || index >= allMoments.length) {
                momentBody.innerHTML = `
                    <div class="moment-empty">
                        <p>瞬间不存在</p>
                    </div>
                `;
                return;
            }
            
            // 显示指定的瞬间
            currentMoment = allMoments[index];
            renderMoment(currentMoment);
        }
        
        // 加载随机瞬间
        function loadRandomMoment() {
            if (allMoments.length === 0) {
                const momentBody = document.getElementById('momentBody');
                momentBody.innerHTML = `
                    <div class="moment-empty">
                        <p>暂无瞬间</p>
                    </div>
                `;
                return;
            }
            
            // 随机选择一个瞬间
            const randomIndex = Math.floor(Math.random() * allMoments.length);
            currentMoment = allMoments[randomIndex];
            renderMoment(currentMoment);
        }
        
        // 渲染瞬间内容
        function renderMoment(moment) {
            const momentBody = document.getElementById('momentBody');
            
            // 获取内容
            const spec = moment.spec || {};
            const status = moment.status || {};
            const content = spec.content || {};
            
            // 获取文本内容
            let textContent = content.html || content.raw || status.content?.html || status.content?.raw || '';
            
            // 获取发布时间
            let publishTime = '未知时间';
            const timeStr = spec.releaseTime || status.releaseTime || spec.createTime || moment.metadata?.creationTimestamp;
            if (timeStr) {
                try {
                    publishTime = new Date(timeStr).toLocaleString('zh-CN', {
                        year: 'numeric',
                        month: '2-digit',
                        day: '2-digit',
                        hour: '2-digit',
                        minute: '2-digit'
                    });
                } catch (e) {
                    publishTime = '未知时间';
                }
            }
            
            let html = `
                <div class="moment-content">
                    <div class="moment-text">${textContent || '无内容'}</div>
            `;
            
            // 显示图片 - 尝试多个可能的字段
            const media = content.medium || status.media || [];
            if (media && media.length > 0) {
                const photos = media.filter(m => {
                    const type = m.type?.name || m.type;
                    return type === 'PHOTO' || type === 'IMAGE' || type === 'photo' || type === 'image';
                });
                if (photos.length > 0) {
                    html += '<div class="moment-images">';
                    photos.forEach(photo => {
                        const url = photo.url || photo.src || photo.originUrl;
                        if (url) {
                            html += `<img src="${url}" alt="瞬间配图" loading="lazy" />`;
                        }
                    });
                    html += '</div>';
                }
            }
            
            html += `
                    <div class="moment-time">
                        <i class="haofont hao-icon-clock"></i>
                        ${publishTime}
                    </div>
                </div>
            `;
            
            momentBody.innerHTML = html;
        }
        
        // 关闭弹窗
        function closeMomentModal() {
            document.getElementById('momentModal').classList.remove('active');
        }
    </script>

</th:block>

</html>

